//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.bfsuol.bfsuolcomponents.file.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bfsuol.yihang.file.entity.FileManager;
import com.bfsuol.yihang.file.domain.FileManagerService;
import com.bfsuol.bfsuolframework.core.controller.SpringControllerSupport;
import com.bfsuol.bfsuolframework.core.controller.json.MessageJson;
import com.bfsuol.bfsuolframework.core.controller.support.Pagination;
import com.bfsuol.bfsuolframework.core.controller.support.QueryParam;
import com.bfsuol.bfsuolframework.core.exception.ValidationException;
import com.bfsuol.bfsuolframework.core.spring.QueryParameter;
import com.bfsuol.bfsuolframework.security.PrivilegeService;
import com.bfsuol.bfsuolframework.security.annotations.SecCreate;
import com.bfsuol.bfsuolframework.security.annotations.SecEdit;
import com.bfsuol.bfsuolframework.security.annotations.SecList;
import com.bfsuol.bfsuolframework.security.annotations.SecPrivilege;
import com.bfsuol.bfsuolframework.security.dao.Menu;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping({"/components/file"})
public class FileManagerController extends SpringControllerSupport {

    @Autowired
    private FileManagerService fileManagerService;

    @SecPrivilege(
            title = "文件管理"
    )
    @RequestMapping("/index")
    @ApiOperation(value = "文件管理首页",httpMethod = "GET")
    public ModelAndView index(Model model){

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("index"));
        return modelAndView;
    }

    @SecList
    @ApiOperation(value = "文件管理列表",httpMethod = "GET")
    @RequestMapping("/list")
    public ModelAndView list(
            @QueryParameter("query") QueryParam query,
            @ModelAttribute("page") Pagination page, Model model){

        com.baomidou.mybatisplus.extension.plugins.pagination.Page page1 = new Page(page.getDefaultCurrentPage(),page.getPageSize());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page fileManagerPage = fileManagerService.page(page1,new QueryWrapper<>());
        page.setItems(fileManagerPage.getRecords());
        page.setTotalRecord((int) fileManagerPage.getTotal());

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("list"));
        return modelAndView;
    }

    @SecCreate
    @RequestMapping("/input")
    public ModelAndView create(@ModelAttribute Menu menu, Model model){
        model.addAttribute("privileges", PrivilegeService.getPrivileges());
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName(getViewNamedPath("input"));
        return modelAndView;
    }




    @SecEdit
    @RequestMapping("/input/{id}")
    public String edit(@PathVariable("id") Long id, Model model){
        FileManager menu = fileManagerService.getById(id);
        model.addAttribute("privileges", PrivilegeService.getPrivileges());
        model.addAttribute(menu);
        return getViewNamedPath("input");
    }

    @RequestMapping({"/save"})
    @SecCreate
    @SecEdit
    public @ResponseBody MessageJson save(@ModelAttribute FileManager fileManager) {


        return MessageJson.information("保存成功");
    }



    @RequestMapping({"/download/{id}"})
    public void download(@PathVariable("id") Long id,
                         HttpServletRequest request,
                         HttpServletResponse response, @RequestParam(value = "realname",required = false) Boolean realname) {
        try {
            FileManager fileManager = (FileManager)fileManagerService.getById(id);
            String filePath = fileManager.getFilePath();
            File file = new File(filePath);
            String fileName = file.getName();
            if(realname != null && realname.booleanValue()) {
                fileName = fileManager.getFileTitle();
            }

            String userAgent = request.getHeader("User-Agent");
            boolean isIE = false;
            if(userAgent.indexOf("MSIE") > 0) {
                isIE = true;
            }

            if(isIE) {
                fileName = new String(fileName.getBytes("gb2312"), "iso-8859-1");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            }

            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException var14) {
            var14.printStackTrace();
        }

    }

    @RequestMapping({"/delete/{id}"})
    @ResponseBody
    public MessageJson delete(@PathVariable("id") Long id) {
        FileManager file = (FileManager)fileManagerService.getById(id);
        if(file == null) {
            throw new ValidationException("删除失败");
        } else {
            String srcPath = file.getFilePath();
            boolean flag = fileManagerService.deleteFile(id.longValue(), srcPath);
            if(flag) {
                return MessageJson.information(new Object[]{"删除成功"});
            } else {
                throw new ValidationException("删除失败");
            }
        }
    }

    @RequestMapping({"/upload"})
    public String upload() {
        return this.getViewNamedPath("upload");
    }

    @RequestMapping({"/getFilesByIds"})
    @ResponseBody
    public List<FileManager> getFilesByIds(@RequestParam("ids") Long[] ids) {
        List<FileManager> list = new ArrayList();
        if(ids != null && ids.length != 0) {
            Long[] var6 = ids;
            int var5 = ids.length;

            for(int var4 = 0; var4 < var5; ++var4) {
                Long id = var6[var4];
                FileManager file = (FileManager)fileManagerService.getById(id);
                if(file != null) {
                    list.add(file);
                }
            }

            return list;
        } else {
            return list;
        }
    }
}
